#!/usr/bin/bash
set -e

# 获取安装版本
echo -n "install maven version(3.8.8): "
read version

download_path="https://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/${version}/binaries/apache-maven-${version}-bin.tar.gz"
binary_name=`basename ${download_path}`

package_dir="/srv/package/"
install_dir="/srv/software/"
custom_env_file="$HOME/.custom_env"

# 创建存放目录
mkdir -p ${package_dir} ${install_dir}

# 检查包是否存在，如果不存在则下载
if [ ! -f "${package_dir}${binary_name}" ]; then
    wget ${download_path} -P ${package_dir}
else
    echo "Package already exists, skipping download."
fi

# 解压和移动文件
if [ -d "${install_dir}maven-${version}" ]; then
    rm -rf "${install_dir}maven-${version}"
fi
tar xf ${package_dir}${binary_name} -C ${install_dir}
mv ${install_dir}apache-maven-${version} ${install_dir}maven-${version}

# 确保自定义环境文件存在
if [ ! -f "${custom_env_file}" ]; then
    touch "${custom_env_file}"
fi

# 移除原来环境变量配置
if grep -q "MAVEN_HOME" ${custom_env_file}; then
    sed -i "/export MAVEN_HOME=/d" ${custom_env_file}
    sed -i "/export PATH=\MAVEN_HOME\/bin:/d" ${custom_env_file}
fi

# 配置环境变量
software_name=$(ls -l ${install_dir} |grep maven |grep ${version} |awk '{print $9}')
cat >> ${custom_env_file} <<-EOF
export MAVEN_HOME=${install_dir}${software_name}
export PATH=\$MAVEN_HOME/bin:\$PATH
EOF

# 确保自定义环境文件被加载
if ! grep -q "source ${custom_env_file}" ~/.bashrc; then
    echo "source ${custom_env_file}" >> ~/.bashrc
fi

source ~/.bashrc

# 安装成功提示
echo "Successfully installed maven..."
